<?php

namespace Gds\VenteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Gds\VenteBundle\Form\BonLivraisonRetourClientType;
use Gds\VenteBundle\Entity\BonLivraisonRetourClient;
use Symfony\Component\HttpFoundation\Response;
use Gds\VenteBundle\Entity\LigneBonLivraisonRetourClient;
use Gds\AchatBundle\Entity\StockAchat;
use Gds\VenteBundle\Entity\Acompte;

class BonLivraisonRetourController extends Controller {

    public function indexAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
        $ref = $societe->getPrefixeBonRetour();
        $ref_num = $societe->getNumeroBonRetour();
        $bon_retour = new BonLivraisonRetourClient();
        $bon_retour->setReference($ref . ' ' . $ref_num);
        $request = $this->getRequest();
        $form = $this->createForm(new BonLivraisonRetourClientType, $bon_retour);
        $user = $this->getUser();
        if ($request->isMethod('POST')) {
            try {
                $articles = json_decode($request->get('articles'));
                if (count($articles->articles) == 0) {
                    $response = new Response(json_encode(array('success' => false)));
                    $response->headers->set('Content-Type', 'application/json');
                    return $response;
                }
                $heure = $request->get('heure');
                $form->bind($request);
                $bon_retour = $form->getData();
                $client = $bon_retour->getClient();

                $date = $bon_retour->getDate();
                $nom_dep = $request->get('departement');
                $departement = $em->getRepository('GdsArticleBundle:Departement')->findOneByNom($nom_dep);
                $bon_retour->setHeure($heure);
                $montant_bl_ttc = 0;
                $montant_noir_ttc = 0;
                foreach ($articles->articles as $json_article) {
                    $article = $em->getRepository('GdsArticleBundle:Article')->find($json_article->id);
                    $stock = $em->getRepository('GdsArticleBundle:Stock')->findOneBy(array('article' => $article, 'departement' => $departement));
                    $quantite = $json_article->quantite;
                    $prix_vente = $json_article->prix_vente;
                    $taux_tva = $json_article->taux_tva;
                    $remise = $json_article->remise;
                    $prix_ttc = $prix_vente * (1 + $taux_tva / 100) * (1 - $remise / 100);
                    $prix_ttc = round($prix_ttc, 3);
                    if ($json_article->bl == "true") {
                        $qte_bl = $quantite;
                        $qte_n = 0;
                        $montant_bl_ttc += $prix_ttc * $quantite;
                        $stock->setQuantiteBlanc($stock->getQuantiteBlanc() + $quantite);
                        $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findOneBy(array('stock' => $stock, 'prix_achat_ttc' => $prix_ttc, 'is_noir' => 0));
                        if ($stock_achat) {
                            $stock_achat->setQuantite($stock_achat->getQuantite() + $quantite);
                        } else {
                            $stock_achat = new StockAchat();
                            $stock_achat->setIsNoir(0);
                            $stock_achat->setPrixAchatTtc($prix_ttc);
                            $stock_achat->setQuantite($quantite);
                            $stock_achat->setStock($stock);
                            $em->persist($stock_achat);
                        }
                    } else {
                        $qte_bl = 0;
                        $qte_n = $quantite;
                        $montant_noir_ttc += $prix_ttc * $quantite;
                        $stock->setQuantiteNoir($stock->getQuantiteNoir() + $quantite);
                        $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findOneBy(array('stock' => $stock, 'prix_achat_ttc' => $prix_ttc, 'is_noir' => 1));
                        if ($stock_achat) {
                            $stock_achat->setQuantite($stock_achat->getQuantite() + $quantite);
                        } else {
                            $stock_achat = new StockAchat();
                            $stock_achat->setIsNoir(1);
                            $stock_achat->setPrixAchatTtc($prix_ttc);
                            $stock_achat->setQuantite($quantite);
                            $stock_achat->setStock($stock);
                            $em->persist($stock_achat);
                        }
                    }
                    $ligne = new LigneBonLivraisonRetourClient();
                    $ligne->setArticle($article);
                    $ligne->setBonLivraisonRetour($bon_retour);
                    $ligne->setPrixUnitaireHt($prix_vente);
                    $ligne->setQuantiteBlanc($qte_bl);
                    $ligne->setQuantiteNoir($qte_n);
                    $ligne->setTauxRemise($remise);
                    $ligne->setTauxTva($taux_tva);
                    $em->persist($ligne);
                }
                $ref_num = $societe->getNumeroBonRetour();
                $societe->setNumeroBonRetour($ref_num + 1);
                $bon_retour->setReference($ref . ' ' . $ref_num);
                $bon_retour->setDepartement($departement);
                $bon_retour->setReste($montant_bl_ttc + $montant_noir_ttc);
                $bon_retour->setMontantBlancTtc($montant_bl_ttc);
                $bon_retour->setMontantNoirTtc($montant_noir_ttc);
                $bon_retour->setUser($user);
                $em->persist($bon_retour);

                $accompte = new Acompte();
                $accompte->setClient($client);
                $accompte->setDate($date);
                $accompte->setHeure($heure);
                $accompte->setMontant($bon_retour->getMontantTtc());
                $accompte->setReference($bon_retour->getReference());
                $accompte->setReste($accompte->getMontant());
                $accompte->setUser($user);
                $em->persist($accompte);

                $em->flush();

                $response = new Response(json_encode(array('success' => true, 'id' => $bon_retour->getId())));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            } catch (Exception $e) {
                $response = new Response(json_encode(array('success' => false)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            }
        }
        return $this->render('GdsVenteBundle:BonRetour:bon_retour.html.twig', array('form' => $form->createView(), 'user' => $user));
    }

    public function getAllBonRetourAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $num = $request->get('numero');
        $client = $request->get('client');
        $date1 = $request->get('date1');
        $date2 = $request->get('date2');
        $ttc1 = $request->get('ttc1');
        $ttc2 = $request->get('ttc2');
        $departement = $request->get('departement');
        $user = $this->getUser();
        if (!$request->get('type') && !$request->get('retour'))
            $departement = $user->getDepartement()->getId();
        $query = $em->getRepository('GdsVenteBundle:BonLivraisonRetourClient')->getResult($num, $client, $date1, $date2, $ttc1, $ttc2, $departement);
        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
                $query, $request->get('page', 1)/* page number */, 10/* limit per page */
        );
        $bons = $em->getRepository('GdsVenteBundle:BonLivraisonRetourClient')->findBy(array('client' => $client));
        if ($request->get('type')) {
            return $this->render('GdsVenteBundle:BonRetour:page_liste_bon_retour.html.twig', array('pagination' => $pagination, 'departement' => $departement, 'bons' => $bons));
        }
        if ($request->get('retour') != "")
            return $this->render('GdsVenteBundle:BonRetour:liste_bon_retour.html.twig', array('pagination' => $pagination, 'departement' => $departement, 'bons' => $bons));
        return $this->render('GdsVenteBundle:BonRetour:all_bon_retour.html.twig', array('pagination' => $pagination, 'departement' => $user->getDepartement()->getId(), 'bons' => null));
    }

    public function showAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $id = $request->get('id');
        $bon_retour = $em->getRepository('GdsVenteBundle:BonLivraisonRetourClient')->find($id);
        $lignes_bon_retour = $em->getRepository('GdsVenteBundle:LigneBonLivraisonRetourClient')->findBy(array('bon_livraison_retour' => $bon_retour));
        $lignes = $em->getRepository('GdsVenteBundle:LigneBonLivraisonRetourClient')->findBy(array('bon_livraison_retour' => $bon_retour), array('taux_tva' => 'ASC'));
        $taxes = array();
        foreach ($lignes as $ligne) {
            $tva = $ligne->getTauxTva();
            $base = $ligne->getQuantite() * $ligne->getPrixUnitaireHt() * (1 - $ligne->getTauxRemise() / 100);
            $montant = $base * $tva / 100;
            $exist = false;
            foreach ($taxes as $k => $taxe) {
                if (!$exist && $taxe['tva'] == $tva) {
                    $taxes[$k]['base']+=$base;
                    $taxes[$k]['montant']+=$montant;
                    $exist = true;
                }
            }
            if (!$exist) {
                $taxe = array();
                $taxe['tva'] = $tva;
                $taxe['base'] = $base;
                $taxe['montant'] = $montant;
                $taxes[count($taxes)] = $taxe;
            }
        }
        return $this->render('GdsVenteBundle:BonRetour:bon_retour_show.html.twig', array('bon_retour' => $bon_retour, 'lignes' => $lignes_bon_retour, 'taxes' => $taxes, 'id' => $id));
    }

    public function printAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
        $prefixe_bl = $societe->getPrefixeBonLivraison();
        $id = $request->get('id');
        $bon_retour = $em->getRepository('GdsVenteBundle:BonLivraisonRetourClient')->find($id);
        $reference = $bon_retour->getReference();
        $numero = str_replace($prefixe_bl, '', $reference);
        $lignes = $em->getRepository('GdsVenteBundle:LigneBonLivraisonRetourClient')->findBy(array('bon_livraison_retour' => $bon_retour));
        $facade = $this->get('ps_pdf.facade');
        $response = new Response();
        $total_brut = 0;
        $remise = 0;
        $total_tva = 0;
        foreach ($lignes as $ligne) {
            $prix = $ligne->getQuantite() * $ligne->getPrixUnitaireHt();
            $total_brut += $prix;
            $remise += $prix * $ligne->getTauxRemise() / 100;
            $total_tva += $prix * (1 - $ligne->getTauxRemise() / 100) * $ligne->getTauxTva() / 100;
        }
        $total_ht = $total_brut - $remise;
        $total_ttc = $total_ht + $total_tva;
        $total_ttc = round($total_ttc, 3);
        $montant_lettre = $this->chiffre_to_lettre($total_ttc);
        $this->render('GdsVenteBundle:BonRetour:bon_retour.pdf.twig', array('lignes' => $lignes, 'numero' => $numero, 'total_ttc' => $total_ttc, 'total_brut' => $total_brut, 'remise' => $remise, 'total_ht' => $total_ht, 'total_tva' => $total_tva, 'montant_lettre' => $montant_lettre, 'bon_retour' => $bon_retour), $response);
        $xml = $response->getContent();
        $content = $facade->render($xml);
        file_put_contents('uploads/bon_retour.pdf', $content);
        exec("printbonretour.vbs");
        return new Response(json_encode(array('success' => true)));
    }

    function int2str($a) {
        if ($a < 0)
            return 'moins ' . $this->int2str(-$a);
        if ($a < 17) {
            switch ($a) {
                case 0: return 'zero';
                case 1: return 'un';
                case 2: return 'deux';
                case 3: return 'trois';
                case 4: return 'quatre';
                case 5: return 'cinq';
                case 6: return 'six';
                case 7: return 'sept';
                case 8: return 'huit';
                case 9: return 'neuf';
                case 10: return 'dix';
                case 11: return 'onze';
                case 12: return 'douze';
                case 13: return 'treize';
                case 14: return 'quatorze';
                case 15: return 'quinze';
                case 16: return 'seize';
            }
        } else if ($a < 20) {
            return 'dix-' . $this->int2str($a - 10);
        } else if ($a < 100) {
            if ($a % 10 == 0) {
                switch ($a) {
                    case 20: return 'vingt';
                    case 30: return 'trente';
                    case 40: return 'quarante';
                    case 50: return 'cinquante';
                    case 60: return 'soixante';
                    case 70: return 'soixante-dix';
                    case 80: return 'quatre-vingt';
                    case 90: return 'quatre-vingt-dix';
                }
            } else if ($a < 70) {
                return $this->int2str($a - $a % 10) . ' ' . $this->int2str($a % 10);
            } else if ($a < 80) {
                return $this->int2str(60) . ' ' . $this->int2str($a % 20);
            } else {
                return $this->int2str(80) . ' ' . $this->int2str($a % 20);
            }
        } else if ($a == 100) {
            return 'cent';
        } else if ($a < 200) {
            return $this->int2str(100) . ' ' . $this->int2str($a % 100);
        } else if ($a < 1000) {
            if (($a % 100) > 0)
                return $this->int2str((int) ($a / 100)) . ' ' . $this->int2str(100) . ' ' . $this->int2str($a % 100);
            else
                return $this->int2str((int) ($a / 100)) . ' ' . $this->int2str(100);
        } else if ($a == 1000) {
            return 'mille';
        } else if ($a < 2000) {
            return $this->int2str(1000) . ' ' . $this->int2str($a % 1000) . ' ';
        } else if ($a < 1000000) {
            return $this->int2str((int) ($a / 1000)) . ' ' . $this->int2str(1000) . ' ' . $this->int2str($a % 1000);
        }
    }

    function chiffre_to_lettre($a) {
        $total = explode(".", $a);
        $dinars = $total[0];
        $millimes = 0;
        if (count($total) == 2) {
            $millimes = $total[1];
            $a = number_format($a, 3);
            $index_point = strpos($a, '.');
            $i = $index_point + 1;
            if ($a[$i] != 0) {
                if ($a[$i + 1] != 0) {
                    if ($a[$i + 2] != 0) {
                        //rien
                    } else {
                        $millimes*=10;
                    }
                } else {
                    if ($a[$i + 2] != 0) {
                        //rien
                    } else {
                        $millimes*=100;
                    }
                }
            } else {
                if ($a[$i + 1] != 0) {
                    if ($a[$i + 2] != 0) {
                        //rien
                    } else {
                        $millimes*=10;
                    }
                } else {
                    if ($a[$i + 2] != 0) {
                        //rien
                    } else {
                        //rien
                    }
                }
            }
        }
        $lettre = $this->int2str($dinars) . " dinars et " . $this->int2str($millimes) . " millimes";
        return $lettre;
    }

}
